'use strict';
const Controller = require('egg').Controller;
class HomeController extends Controller {





async chat() {
const { ctx } = this;
// const { log } = require("console");
 let id=ctx.request.query;  
const useWebSocket = require("ws")
 
        // 下单
    ; ((Ws) => {
        const server = new Ws.Server({ port: id.doctorID })
        
        const init = () => {
            bindEvent()
        }

        init()

        // 监听链接
        function bindEvent() {
            server.on("connection", listen)
        }
        function listen(ws) {
            ws.on("message", msg)
            console.log("链接成功");
        }
        
        // 监听收到的消息，参数msg是用户发送过来的
        function msg(msg) {
            let _msg = msg.toString();
            // server.clients是连接到该服务器的所有客户端，是一个数组
            server.clients.forEach((e) => {
                e.send(_msg)   
            })
            
           
        }
    
    })(useWebSocket);


    ctx.body={
        info:"ok",
        code:200
    }
 }

//监听订单
 async order() {
    const { ctx } = this;

    //  let id=ctx.request.query;  
    const useWebSocket = require("ws")
    
            // 下单
        ; ((Ws) => {
            const server = new Ws.Server({ port: 1000 })
            
            const init = () => {
                bindEvent()
            }
    
            // 监听链接
            function bindEvent() {
                server.on("connection", listen)
            }
            function listen(ws) {
                ws.on("message", msg)
                console.log("链接成功100,order");
            }
            
            // 监听收到的消息，参数msg是用户发送过来的
            function msg(msg) {
                let _msg = msg.toString();
                // server.clients是连接到该服务器的所有客户端，是一个数组
                server.clients.forEach((e) => {
                    e.send(_msg)   
                })
                
               
            }
            init()
        })(useWebSocket);
    
    
        ctx.body={
            info:"ok",
            code:200
        }
     }


    //  获取医生状态
     async getOnline() {
        let doctorID=this.ctx.query.did
        let sql = `select * from goods WHERE id='${doctorID}'`
        let res = await this.ctx.app.mysql.query(sql)
        this.ctx.body={
            info:"ok",
            code:200,
            online:res[0].online
        }
     }


     async Offline(){
        let doctorID=this.ctx.query.did
        let sql=`UPDATE goods SET online=0  WHERE id=${doctorID};`
        this.ctx.app.mysql.query(sql)
        this.ctx.body={
            info:"ok"
        }
     }
   
     async goOnline(){
        let doctorID=this.ctx.query.did
        
        let sql=`UPDATE goods SET online=1  WHERE id=${doctorID};`
        this.ctx.app.mysql.query(sql)
        this.ctx.body={
            info:"ok"
        }
        
    }
  

}
module.exports = HomeController;